﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;
using System.Threading;

namespace PIBV
{
    public class PID_Database : PID_BaseClass, IEnumerator<string>
    {
        public const string TableNameLoop = "LOOP";

        public PID_Database() : base()
        {
        }

        public void FillData()
        {
            if (ds.Tables.Contains(TableNameLoop))
            {
                ds.Tables.Remove(TableNameLoop);
            }
            
            OleDbDataAdapter dAdapter = new OleDbDataAdapter();
            dAdapter.SelectCommand = new OleDbCommand("SELECT * FROM LOOP", Connection);
            dAdapter.Fill(ds, TableNameLoop);
        }

        public DataTable GetLoops()
        {
            return ds.Tables[TableNameLoop];        
        }

        public delegate string GetDocument(string url);

        public void SaveDrawing(long loopId, string fileName)
        {
            object bExist = ExecuteScalar("SELECT * FROM DRAWING WHERE LoopID="+loopId);
            if (bExist == null)
            { 
                //insert record
                ExecuteQuery(String.Format("INSERT INTO DRAWING (LoopID) VALUES ({0})",loopId));
            }

            string fileExt = System.IO.Path.GetExtension(fileName).ToLower();

            ExecuteQuery(String.Format("UPDATE DRAWING SET {0}' WHERE LoopID = {1}",
                    ((fileExt == ".pdf") ? "D_FILE_PDF='" : "D_FILE_DGN='")+fileName,loopId));
        }

        #region IDisposable Members

        void IDisposable.Dispose()
        {
            throw new NotImplementedException();
        }

        #endregion

        public long CurrentID
        {
            get { return Convert.ToInt32(ds.Tables[TableNameLoop].Rows[_pos]["LoopID"]); }
        }

        #region IEnumerator<string> Members

        string IEnumerator<string>.Current
        {
            get { return ds.Tables[TableNameLoop].Rows[_pos]["PID"].ToString(); }
        }

        #endregion

        #region IEnumerator Members

        int _pos = -1;

        object IEnumerator.Current
        {
            get { 
                    return ds.Tables[TableNameLoop].Rows[_pos]["PID"].ToString();
                }
        }

        bool IEnumerator.MoveNext()
        {
            _pos++;
            return ds.Tables[TableNameLoop].Rows.Count>0 && ds.Tables[TableNameLoop].Rows.Count > _pos;
        }

        void IEnumerator.Reset()
        {
            _pos = -1;
            FillData();
        }

        #endregion
    }
}
